package com.shinemo.mpush.alloc.http;

import java.io.IOException;
import java.io.OutputStream;

import com.mpush.api.Constants;
import com.sun.net.httpserver.HttpExchange;

public class HttpResponse {

	private static String jsonContentType = "application/json;charset=UTF-8";
	private static String plainTextContentType = "text/plain;charset=UTF-8";
	
	private HttpResponse() {
		
	}

	public static void writeJson(HttpExchange httpExchange, String response) throws IOException {
		write(httpExchange, response.getBytes(Constants.UTF_8), jsonContentType);
	}

	public static void write(HttpExchange httpExchange, String response) throws IOException {
		write(httpExchange, response.getBytes(Constants.UTF_8), plainTextContentType);
	}

	public static void write(HttpExchange httpExchange, byte[] data, String contentType) throws IOException {
		httpExchange.getResponseHeaders().set("Content-Type", contentType);
		httpExchange.sendResponseHeaders(200, data.length);// 200, content-length
		OutputStream out = httpExchange.getResponseBody();
		out.write(data);
		out.close();
		httpExchange.close();
	}
}
